#!/usr/bin/env python
#-*- coding: utf-8 -*-

import urllib2
import urllib
import re
import random
import time


class E100(object):
    JSESSIONID=''

    def __init__(self):
        self.JSESSIONID=''
        self.getVerifyCode(isLogin=False)

    def getVerifyCode(self,savePath='./e100.jpg', isLogin=True):
        url="http://www.gd.chinamobile.com/image?sds=%s"% random.random() #16 bit, but python has 17 bit.
        headers={ 
                  'Host':'www.gd.chinamobile.com',
                  'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8',
                  'Accept':'image/png,image/*;q=0.8,*/*;q=0.5',
                  'Accept-Language':'zh-cn,zh;q=0.5',
                  'Accept-Encoding':'gzip,deflate',
                  'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7',
                  'Keep-Alive':'300',
                  'Connection':'keep-alive',
                  'Referer':'https://www.gd.chinamobile.com/e100/index.jsp',
                  #'Cookie':'JSESSIONID=%s' % self.JSESSIONID,
                }
        if isLogin:
            headers['Cookie'] = 'JSESSIONID=%s' % self.JSESSIONID
        print headers
        req=urllib2.Request(url=url, headers=headers)
        conn = urllib2.urlopen(req)
        header=str(conn.info())
        print header
        res = conn.read()
        fobj=open(savePath, 'wb')
        fobj.write(res)
        fobj.close()
        #self.JSESSIONID = header.getheader('Set-Cookie')
        if not isLogin:
            self.JSESSIONID = re.findall(r"Set-Cookie: JSESSIONID=(.*); Path=/",header,re.M)[0]
            print self.JSESSIONID
    
    def login(self, cellphone, passwd, verifyCode):

        url="http://www.gd.chinamobile.com/ServicesServlet/LOGIN"

        request_json="""{"operation":"login","isProtocol":true,"_dl100Mobile":"","_loginInfo":"{\\"_loginType\\":\\"2\\",\\"_logonName\\":\\"%s"""% cellphone +"""\\",\\"_password\\":\\"%s"""% passwd +"""\\",\\"_smsRND\\":\\"\\",\\"isProtocol\\":true,\\"_login_backurl\\":\\"/e100/index.jsp\\",\\"_channel\\":8,\\"_imageCode\\":\\"%s"""% verifyCode +"""\\"}"}"""

        data = urllib.urlencode([('_request_json','%s'% request_json),('_channel', '8')])
        #data = """_request_json=%257B%2522operation%2522%253A%2522login%2522%252C%2522isProtocol%2522%253Atrue%252C%2522_dl100Mobile%2522%253A%2522%2522%252C%2522_loginInfo%2522%253A%2522%257B%255C%2522_loginType%255C%2522%253A%255C%25222%255C%2522%252C%255C%2522_logonName%255C%2522%253A%255C%2522%s"""% cellphone+""" %255C%2522%252C%255C%2522_password%255C%2522%253A%255C%2522%s"""% passwd+"""%255C%2522%252C%255C%2522_smsRND%255C%2522%253A%255C%2522%255C%2522%252C%255C%2522isProtocol%255C%2522%253Atrue%252C%255C%2522_login_backurl%255C%2522%253A%255C%2522%252Fe100%252Findex.jsp%255C%2522%252C%255C%2522_channel%255C%2522%253A8%252C%255C%2522_imageCode%255C%2522%253A%255C%2522%s"""% verifyCode+"""%255C%2522%257D%2522%257D&_channel=8"""
        print data
        print len(data)
        
        headers={
                  'Host':'www.gd.chinamobile.com',
                  'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8',
                  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                  'Accept-Language':'zh-cn,zh;q=0.5',
                  'Accept-Encoding':'gzip,deflate',
                  'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7',
                  'Keep-Alive':'300',
                  'Connection':'keep-alive',
                  'Referer':'https://www.gd.chinamobile.com/e100/index.jsp',
                  'Cookie':'JSESSIONID=%s' % self.JSESSIONID,
                  'Content-Type':'application/x-www-form-urlencoded',
                  #'Content-Length':'%s' % len(data),
                }
        print headers
        req = urllib2.Request(url=url, headers=headers, data=data)
        conn = urllib2.urlopen(req)
        head = conn.info()
        body = conn.read()
        print head
        print body
    
    def getRandomSMS(self):
        url="http://www.gd.chinamobile.com/login/sendSMSRND.jsp?_logonName=E100_USER&_r=%s"% random.random()
        data=''
        headers={
                  'Host':'www.gd.chinamobile.com',
                  'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8',
                  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                  'Accept-Language':'zh-cn,zh;q=0.5',
                  'Accept-Encoding':'gzip,deflate',
                  'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7',
                  'Keep-Alive':'300',
                  'Connection':'keep-alive',
                  'Referer':'https://www.gd.chinamobile.com/e100/index.jsp',
                  'Cookie':'JSESSIONID=%s' % self.JSESSIONID,
                  'Pragma':'no-cache',
                  'Cache-Control':'no-cache',
                  'Content-Length':'%s' % len(data),
                }
        
        print headers
        req = urllib2.Request(url=url, headers=headers, data=data)
        conn = urllib2.urlopen(req)
        head = conn.info()
        body = conn.read()
        print head
        print body

    def sendSMS(self, to, msg, logoCode):
        timeStamp = getTimeStamp()
        sendTime = getSendTime()
        url="http://www.gd.chinamobile.com/e100/SMS/Send?timeStamp=%s"% timeStamp
        request_json="""{"operation":"SMS_SEND","smsMessage":"{\\"person\\":\\"%s"""% to +"""\\",\\"content\\":\\"%s"""% msg+"""\\",\\"type\\":\\"0\\",\\"time\\":\\"%s"""% sendTime+"""\\",\\"payment\\":\\"0\\",\\"logoCode\\":\\"%s"""% logoCode +"""\\"}"}"""

        data = urllib.quote(request_json)
        print data
        print len(data)
        
        headers={
                  'Host':'www.gd.chinamobile.com',
                  'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8',
                  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                  'Accept-Language':'zh-cn,zh;q=0.5',
                  'Accept-Encoding':'gzip,deflate',
                  'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7',
                  'Keep-Alive':'300',
                  'Connection':'keep-alive',
                  'Referer':'https://www.gd.chinamobile.com/e100/index.jsp',
                  'Content-Length':'%s' % len(data),
                  'Content-Type':'text/plain; charset=UTF-8',
                  'Cookie':'userSrcUrlL=undefined; userSrcUrlR=undefined; JSESSIONID=%s' % self.JSESSIONID,
                  'Pragma':'no-cache',
                  'Cache-Control':'no-cache',
                }
       
        print headers
        req = urllib2.Request(url=url, headers=headers, data=data)
        conn = urllib2.urlopen(req)
        head = conn.info()
        body = conn.read()
        print head
        print body
        
def getTimeStamp():
    timeStampFlt=time.time()
    timeStamp = str(timeStampFlt).replace('.','0')
    return timeStamp
def getSendTime():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())[:17]+"00.000000"
